package org.iabako.client.ui.form.business.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.IField;
import org.iabako.client.ui.layout.template.Popup;
import org.iabako.client.ui.layout.widget.payment.PaymentResume;
import org.iabako.client.ui.layout.widget.sale.SaleTable;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.Client;
import org.iabako.shared.entity.business.Installment;
import org.iabako.shared.entity.business.Payment;
import org.iabako.shared.iservice.business.ClientServiceAsync;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jose on 12/09/14.
 */
public class ClientSalesForm extends AbstractForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, ClientSalesForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    @UiField
    HTMLPanel salesPanel;
    @UiField
    PaymentResume paymentResume;

    Client client;
    SaleTable sales;
    List<Payment> paymentsList = new ArrayList<Payment>();
    List<Installment> installmentsList = new ArrayList<Installment>();


    public ClientSalesForm() {
        initWidget(binderForm.createAndBindUi(this));
    }

    public void setClient(final Client client) {
        this.client = client;
    }

    protected void getPaymentsAndInstallments() {
        ClientServiceAsync.Util.getInstance().getPayments(client, new IabakoAsyncCallback<List<Payment>>() {
            public void onSuccess(List<Payment> result) {
                paymentsList = result;

                ClientServiceAsync.Util.getInstance().getInstallments(client, new IabakoAsyncCallback<List<Installment>>() {
                    public void onSuccess(List<Installment> result) {
                        installmentsList = result;
                        paymentResume.setInformation(null, paymentsList, installmentsList);
                        super.onSuccess(result);
                    }
                });

                super.onSuccess(result);
            }
        });
    }

    public void refreshSales() {
        sales.refreshSearch();
        getPaymentsAndInstallments();
    }

    @Override
    public void initialize() {
        if (client != null && sales == null) {
            sales = new SaleTable(parentForm, client);
            sales.show(salesPanel);
            getPaymentsAndInstallments();
        }
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return null;
    }

    @Override
    protected AbstractEntity getEntity() {
        return null;
    }

    @Override
    public boolean validate() {
        return false;
    }
}
